import axios from 'axios'
import { Message } from 'element-ui'
import { UserModule } from '@/store/modules/user'
import { RequestQueryBuilder, CreateQueryParams } from '@nestjsx/crud-request'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000
})

// Request interceptors
service.interceptors.request.use(
  (config) => {
    if (UserModule.token) {
      config.headers.Authorization = 'Bearer ' + UserModule.token
    }
    return config
  },
  (error) => {
    Promise.reject(error)
  }
)

// Response interceptors
service.interceptors.response.use(
  (response) => {
    const res = response.data
    if (res.error) {
      Message({
        message: res.error || 'Error',
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return response
    }
  },
  (error) => {
    Message({
      // message: error.message,
      message: error.response.data.error || error.message || 'Unknow response error',
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

const crudParamsSerializer = (params: CreateQueryParams) => RequestQueryBuilder.create(params).query()

export { service, crudParamsSerializer }
